#include "upgradeform.h"
#include "ui_upgradeform.h"

UpgradeForm::UpgradeForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UpgradeForm)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/image/logo.ico"));

    updataStatTimer = new QTimer;
    connect(updataStatTimer,SIGNAL(timeout()),this,SLOT(updataStatTimerCallBack()));//更新端口号
    ui->newVersions->setValidator(new QIntValidator(0,9999999,this));
}

UpgradeForm::~UpgradeForm()
{
    delete ui;
}

void UpgradeForm::init(void){
    ui->updateStat->setText("Enpty");
    ui->progressBar->setValue(0);
    ui->progressBar->update();
    ui->startSendBin->setEnabled(true);
}

void UpgradeForm::showEvent(QShowEvent *event) // 窗体显示在屏幕上时
{
    ui->updateStat->setText("");
    ui->progressBar->setValue(0);
    ui->progressBar->update();
    uint8_t data[5] = {0xFE, 0x02, 0x00,0x00,0x02};
    emit serialWriteData(data, 5);
}
void UpgradeForm::hideEvent(QHideEvent *event) // 窗体从屏幕上消失时，(包括最小化，不包括被遮挡)
{
    ui->updateStat->setText("");
    ui->progressBar->setValue(0);
    ui->progressBar->update();
}


void UpgradeForm::serialReadMsg(DataPack *data)
{
    updataStatTimer->stop();
    // 固件信息
    if(data->package.type==MSG_VERSION_REPLY){
        qDebug()<<"固件版本信息"<<data->package.payload[0]<<"  "<<data->package.payload[1]<<"  "<<data->package.payload[2];
        version = (uint32_t)((uint32_t)data->package.payload[0]<<16 | (uint32_t)data->package.payload[1]<<8 | data->package.payload[2]);
        ui->binVersions->setText(QString::number(version));
    }
    else if(data->package.type==MSG_VERSION_REQ ){  // 接收到固件版本信息请求
        qDebug()<<"接收到固件版本信息请求";
        getBinMsg();
        QString ver = ui->newVersions->text();
        sendPackSize(binSize, packTotal, ver.toUInt());
        ui->progressBar->setMaximum(packTotal);
    }
    else if(data->package.type==MSG_FIRMWARE_REQ){  // 接收到固件版本信息请求
        uint16_t index;
        if(data->package.len<=127)
        {
            index = data->package.payload[0] & 0x00ff;
        }
        else if(data->package.len==2){
            index = (uint16_t)(data->package.payload[0]<<8 | data->package.payload[1]);
        }
        ui->updateStat->setText("Loading...");
        qDebug()<<"下发第"<<index<<"包数据";
        if(index==packTotal)        currentPackSize = binSize%200;
        else                        currentPackSize =  200;

        ui->progressBar->setValue(index);
        sendBin(index, bin+(index-1)*200, currentPackSize);
        updataStatTimer->stop();
        updataStatTimer->start(3000);
    }
    else if(data->package.type==MSG_UPDATE_FINISH){
        ui->progressBar->setValue(packTotal);
        version = (uint32_t)((uint32_t)data->package.payload[0]<<16 | (uint32_t)data->package.payload[1]<<8 | data->package.payload[2]);
        ui->binVersions->setText(QString::number(version));
        ui->updateStat->setText("Finish");
        ui->startSendBin->setEnabled(true);

    }
}


void UpgradeForm::updataStatTimerCallBack(void)
{
    updataStatTimer->stop();
    ui->updateStat->setText("Updata Error");
    ui->startSendBin->setEnabled(true);
}

void UpgradeForm::on_fileCheck_clicked()
{
    filePath = QFileDialog::getOpenFileName(this, tr("文件对话框！"), "C:/appBin", tr("bin文件(*bin)"));
    ui->fileEdit->setText(filePath);
}


/**
 *发送固件数据包长度信息，
 *
 */
void UpgradeForm::on_startSendBin_clicked()
{
    uint8_t data[5] = {0xFE,MSG_LOAD_START ,0x00,0x00,MSG_LOAD_START};
    emit serialWriteData(data, 5);
    ui->startSendBin->setEnabled(false);
    ui->updateStat->setText("Start...");
    ui->progressBar->setValue(0);
    updataStatTimer->start(3000);

}

void UpgradeForm::getBinMsg(void)
{
    filePath = ui->fileEdit->text();
    if(!fileUnit.fileExists(filePath))
    {
        QMessageBox::information(this, "提示", "请选择文件", QMessageBox::Yes, QMessageBox::Yes);
        packTotal=0;
        binSize=0;
    }else{
        binFile = fileUnit.readBin(filePath);
        binSize = binFile.size();

        bin = (uint8_t *)binFile.data();

        // 计算数据包长度
        packTotal =  binSize/PACK_LEN;
        if(binSize%PACK_LEN>0)     packTotal++;
        ui->progressBar->setRange(1, packTotal);

        qDebug()<<"binSize:"<<binSize<<"  "<<"packTotal:"<<packTotal;
//        ui->binSize->setText(QString::number(binSize));
//        ui->packSize->setText(QString::number(packTotal));
    }
}


// 发送固件版本和数据长度
void UpgradeForm::sendPackSize(uint16_t size,uint16_t packSize,uint32_t ver)
{
    DataPack dataPack;
    dataPack.package.type= MSG_VERSION_REPLY;
    dataPack.package.len = 5;
    dataPack.package.payload.clear();
    dataPack.package.payload.append((ver>>16)&0x000000ff);
    dataPack.package.payload.append((ver>>8)&0x000000ff);
    dataPack.package.payload.append(ver&0x000000ff);
    dataPack.package.payload.append((packSize>>8)&0x00ff);
    dataPack.package.payload.append(packSize&0x00ff);
    dataPack.checkSum();
    uint8_t *buf = dataPack.getArrayData();
    emit  serialWriteData(buf, dataPack.getArrayDataLen());
}

void UpgradeForm::sendBin(uint16_t num,uint8_t *buf,uint16_t len)
{
    DataPack dataPack;
    dataPack.package.type=MSG_FIRMWARE_REPLY;
    dataPack.package.len = len+2;
    dataPack.package.payload.clear();
    dataPack.package.payload.append((num>>8)&0x00ff);
    dataPack.package.payload.append(num&0x00ff);
    for (int i=0;i<len;i++) {
        dataPack.package.payload.append(buf[i]);
    }
    dataPack.checkSum();
    uint8_t *buff = dataPack.getArrayData();
    emit serialWriteData(buff, dataPack.getArrayDataLen());
}
